using FluentValidation;

using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;

using Volo.Abp.DependencyInjection;

using WL.Think.Abp.Localization;

namespace WL.Think.Abp.Validators
{
    /// <summary>
    /// 基础认证器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ThinkBaseValidator<T> : AbstractValidator<T> where T : class
    {
        protected IAbpLazyServiceProvider ServiceProvider { get; }
        protected IStringLocalizer L { get; private set; }
        protected ILogger Logger { get; private set; }

        protected ThinkBaseValidator(IAbpLazyServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider;
            InitLogger();
            InitLocalizer();
            CreateRule();
        }

        protected abstract void CreateRule();

        /// <summary>
        /// 配置本地化资源类
        /// </summary>
        /// <returns></returns>
        protected virtual Type LocalizationResource()
        {
            return typeof(ThinkResource);
        }

        /// <summary>
        /// 获取通过依赖注入的服务
        /// </summary>
        /// <typeparam name="TService">对象类型</typeparam>
        /// <returns></returns>
        protected TService GetRequiredService<TService>() where TService : class
        {
            return ServiceProvider.LazyGetRequiredService<TService>();
        }

        /// <summary>
        /// 获取通过依赖注入的服务
        /// </summary>
        /// <typeparam name="TService">对象类型</typeparam>
        /// <returns></returns>
        protected TService? GetService<TService>() where TService : class
        {
            return ServiceProvider.LazyGetService<TService>();
        }

        /// <summary>
        /// 初始化本地化解析器
        /// </summary>
        private void InitLocalizer()
        {
            var factory = GetRequiredService<IStringLocalizerFactory>();
            L = factory.Create(LocalizationResource());
        }

        /// <summary>
        /// 初始化日志记录器
        /// </summary>
        private void InitLogger()
        {
            var factory = GetRequiredService<ILoggerFactory>();
            Logger = factory.CreateLogger<T>();
        }
    }
}
